<template>
  <div class="roles-container">
    <!-- 头部的面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体区域 -->
    <el-card>
      <!-- 头部按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表展示 -->
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand">
          <template #default="scope">
            <el-row :class="['bdBottom', i1 === 0 ? 'bdTop' : '', 'vcenter']" v-for="(level1, i1) in scope.row.children" :key="level1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, level1.id)">{{ level1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdTop', 'vcenter']" v-for="(level2, i2) in level1.children" :key="level2.id">
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, level2.id)">{{ level2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="level3 in level2.children" :key="level3.id" closable @close="removeRightById(scope.row, level3.id)">{{ level3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditRoleDialog(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteRole(scope.row)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="small" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限弹出对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" :props="treeProps" ref="treeRef" show-checkbox node-key="id" default-expand-all :default-checked-keys="rightsKey"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色弹出对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="resetAddRoleForm">
      <!-- form表单 -->
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色弹出对话框 -->
    <el-dialog title="添加角色" :visible.sync="editRoleDialogVisible" width="50%">
      <!-- form表单 -->
      <el-form :model="editRoleForm" :rules="editRoleFormRules" ref="editRoleFormRef" label-width="100px">
        <el-form-item label="角色id" prop="roleId">
          <el-input v-model="editRoleForm.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList()
  },
  data() {
    return {
      // 存放角色列表
      rolesList: [],
      // 控制 分配权限弹出对话框的 显示与隐藏
      setRightDialogVisible: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 保存三级权限下的id值
      rightsKey: [],
      // 保存角色的id
      roleId: '',
      /* 添加角色弹出对话框 */
      addRoleDialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      /* 编辑角色弹出对话框 */
      editRoleDialogVisible: false,
      editRoleForm: {},
      editRoleFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败!')
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 删除权限
    async removeRightById(role, rightId) {
      const confirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') return this.$message.info('取消删除!')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败!')
      // 不建议调用this.getRolesList() 因为每调用一次这个函数都会导致列表重新渲染 我们希望页面显示的是删掉某个tag后的结果
      // 因此 我们可以将返回的结果直接赋值
      role.children = res.data
    },
    // 分配权限 按钮响应事件
    async showSetRightDialog(role) {
      // 获取roleId
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightsList = res.data
      // console.log(this.rightsList)
      this.rightsKey = []
      this.getRightsKey(role, this.rightsKey)
      this.setRightDialogVisible = true
    },
    // 获取角色下所有三级权限的id
    getRightsKey(node, rightsKey) {
      // 如果当前节点不存在children属性 说明为三级权限结点，则将id值保存在rightsKey数组中
      if (!node.children) return rightsKey.push(node.id)
      // 否则 说明存在children属性,则循环变量每一项children并进行递归
      node.children.forEach(item => {
        this.getRightsKey(item, rightsKey)
      })
    },
    // 用于分配权限确认
    async allotRights() {
      const keys = [...this.$refs.treeRef.getHalfCheckedKeys(), ...this.$refs.treeRef.getCheckedKeys()]
      const keysStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: keysStr
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败!')
      // 关闭对话框
      this.setRightDialogVisible = false
      // 提示成功
      this.$message.success('更新成功!')
      // 权限保存成功后则重新刷新角色列表
      this.getRolesList()
    },
    /* 添加角色 */
    addRole() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败!')
        this.$message.success(res.meta.msg)
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },
    /* 重置添加角色表单 */
    resetAddRoleForm() {
      this.$refs.addRoleFormRef.resetFields()
    },
    /* 删除角色 */
    deleteRole(role) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async confirm => {
          const { data: res } = await this.$http.delete(`roles/${role.id}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败!')
          this.$message.success(res.meta.msg)
          this.getRolesList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /* 显示编辑角色对话框 */
    async showEditRoleDialog(role) {
      const { data: res } = await this.$http.get(`roles/${role.id}`)
      if (res.meta.status !== 200) return this.$message.error('获取该角色信息失败!')
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    async editRole() {
      console.log(this.editRoleForm, 'ok')
      const { data: res } = await this.$http.put(`roles/${this.editRoleForm.roleId}`, {
        roleName: this.editRoleForm.roleName,
        roleDesc: this.editRoleForm.roleDesc
      })
      if (res.meta.status !== 200) return this.$message.error('编辑角色失败!')
      this.$message.success('更新角色成功!')
      this.editRoleDialogVisible = false
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
